//
//  ViewController.m
//  Barrier线程阻塞
//
//  Created by 伍银荣 on 2021/8/26.
//  Copyright © 2021 com.WYR. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
{
    dispatch_queue_t _queue;
}

@property (nonatomic, strong) NSMutableArray *photoList;

@end

@implementation ViewController

-(NSMutableArray *)photoList {
    if (!_photoList) {
        _photoList = [NSMutableArray array];
    }
    return _photoList;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //初始化并发队列
    _queue = dispatch_queue_create("hm", DISPATCH_QUEUE_CONCURRENT);
    
    for (int i = 1; i <= 10; i++) {
        [self downloadImage:i];
    }
}

//模拟从网络上下载很多图片,并且添加到NSMutableArray类型的数组中
//将数据添加到NSMutableArray类型的数组中,线程是不安全的
- (void)downloadImage:(int)index {
    //模拟下载图片,下载图片是一个耗时操作,所以应该放到子线程中执行
    //使用barrier只能使用并发队列
    dispatch_async(_queue, ^{
        NSString *fileName = [NSString stringWithFormat:@"%02d.jpg",index];
        NSString *path = [[NSBundle mainBundle]pathForResource:fileName ofType:nil];
        UIImage *img = [UIImage imageWithContentsOfFile:path];
        //等待之前队列中的任务完成后,再执行barrier中的代码(实现先下载图片再添加图片)
        dispatch_barrier_async(self->_queue, ^{
            //把图片添加到可变数组中
            [self.photoList addObject:img];
            NSLog(@"添加完成--%@--%@",fileName, [NSThread currentThread]);
        });
        NSLog(@"下载完成--%@--%@",fileName, [NSThread currentThread]);
    }) ;
    
}



@end
